package com.doujiang.sys.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.doujiang.sys.constant.SysConstant;
import com.doujiang.sys.domain.User;
import com.doujiang.sys.domain.Uservo;
import com.doujiang.sys.service.IUserService;
import com.doujiang.sys.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author：豆浆
 * @name :LoginController
 * @Date：2023/12/18 19:56
 */

@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    private IUserService userService;
    @RequestMapping("toLogin")
    public String toLogin(){
        return "system/main/login";
    }


    /**
     * 登陆方法
     */
    @RequestMapping("login")
    public String login(Uservo userVo, Model model){
        //获取验证码
        String code =WebUtils.getHttpSession().getAttribute("code").toString();
        //判断用户数的验证码和session中的验证码是否一致
        if(userVo.getCode().equals(code)){
            //如果验证码一致，就要验证用户名或密码是否正确
            User user = userService.login(userVo);
            System.out.println("user = " + user);
            if(null!=user){
                //放⼊到session
                //如果用户存在说明登录成功，需要跳转到index页面
                WebUtils.getHttpSession().setAttribute("user",user);
                return "system/main/index";
            }else {
                //没有查到用户,说明用户名和密码错误,需要跳转到login页面
                model.addAttribute("error",SysConstant.USER_LOGIN_ERROR_MSG);
                return "system/main/login";
            }
        }else {
            //验证码错误，跳转到index页面
            model.addAttribute("error",SysConstant.USER_LOGIN_CODE_ERROR_MSG);
            return "system/main/login";
        }
    }


    //获取验证码
    @RequestMapping("getCode")
    public void getCode(HttpServletResponse response, HttpSession
            session) throws IOException {
        //定义图形验证码的⻓和宽,符号,干扰线
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116,36,4,5);

        //生成的验证码放到session
        session.setAttribute("code",lineCaptcha.getCode());
        //获取输出流
        ServletOutputStream outputStream =
                response.getOutputStream();
        //将数据以图片的方式输出
        ImageIO.write(lineCaptcha.getImage(),"JPEG",outputStream);
    }



}
